# -*- coding: utf-8 -*-
import time

from tablestore import *

from GKModel.AuthModel import AuthModel
from GKModel.Category import Category
from GKModel.Category import CATEGORY_TUTOR_MATCH


class TutorMatch(AuthModel):
    TABLE_NAME = 'TutorMatches'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.__category = Category(**kwargs)

    def create_match(self, match_type: str, **kwargs):
        if match_type is None or len(match_type) == 0:
            raise ValueError(1000024, 'need match type')

        if 'name' not in kwargs or \
                'phone' not in kwargs or \
                kwargs['name'] is None or \
                kwargs['phone'] is None or \
                len(kwargs['name']) == 0 or \
                len(kwargs['phone']) == 0:
            raise ValueError(1000024, 'Info not complete')

        if match_type.lower() == 'normal':
            category = self.__category.query_by_key_name(CATEGORY_TUTOR_MATCH, 'System', 'Normal')
        elif match_type.lower() == 'dna':
            category = self.__category.query_by_key_name(CATEGORY_TUTOR_MATCH, 'System', 'DNA')
        else:
            raise ValueError(1000025, 'Missing Match Type')

        now = int(time.time())
        requirement = kwargs['requirement'] if 'requirement' in kwargs else ''
        primary_key = [('create_time', now), ('category_id', category['cid']), ('mid', PK_AUTO_INCR)]
        attribute_columns = [
            ('uid', self.uid),
            ('name', kwargs['name']),
            ('phone', kwargs['phone']),
            ('requirement', requirement)
        ]
        row = Row(primary_key, attribute_columns)
        try:
            consumed, return_row = self.ots_client.put_row(TutorMatch.TABLE_NAME, row)
            return self.client.update_token()
        except OTSClientError as e:
            raise ValueError(1000009, e.get_error_message())
        except OTSServiceError as e:
            raise ValueError(1000009, e.get_error_message())

    def query_match_list(self, match_type: str=None, next_start_primary_key=None, limit=10):
        if match_type is None:
            cid_start = INF_MAX
            cid_end = INF_MIN
        elif match_type.lower() == 'normal':
            category = self.__category.query_by_key_name(CATEGORY_TUTOR_MATCH, 'System', 'Normal')
            cid_start = category['cid']
            cid_end = category['cid']
        elif match_type.lower() == 'dna':
            category = self.__category.query_by_key_name(CATEGORY_TUTOR_MATCH, 'System', 'DNA')
            cid_start = category['cid']
            cid_end = category['cid']
        else:
            cid_start = INF_MAX
            cid_end = INF_MIN
        inclusive_start_primary_key = [('create_time', INF_MAX), ('category_id', cid_start), ('mid', INF_MAX)] \
            if next_start_primary_key is None else next_start_primary_key
        exclusive_end_primary_key = [('create_time', INF_MIN), ('category_id', cid_end), ('mid', INF_MIN)]
        columns_to_get = []
        cond = SingleColumnCondition('uid', self.uid, ComparatorType.EQUAL)

        try:
            consumed, next_start_primary_key, row_list, next_token = self.ots_client.get_range(
                table_name=TutorMatch.TABLE_NAME,
                direction=Direction.BACKWARD,
                inclusive_start_primary_key=inclusive_start_primary_key,
                exclusive_end_primary_key=exclusive_end_primary_key,
                columns_to_get=columns_to_get,
                limit=limit,
                column_filter=cond,
                max_version=1
            )

            result = []
            for row in row_list:
                item = dict(row.primary_key)
                for att in row.attribute_columns:
                    item[att[0]] = att[1]
                result.append(item)

            return result, next_start_primary_key, self.client.update_token()

        except OTSServiceError as e:
            raise ValueError(1000009, e.get_error_message())
        except OTSClientError as e:
            raise ValueError(1000009, e.get_error_message())


def new(**kwargs) -> TutorMatch:
    return TutorMatch(**kwargs)

